<?php

namespace app\service;

use Exception;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;

class JwtAuth
{
    public static function createToken($user_id, $user_type = 'admin')
    {
        $key = 'example_key';
        $payload = [
            'iss' => $user_id, //签发者 可以为空
            'aud' => $user_id, // 面向的用户,可以为空
            'iat' => time(), // 签发的时间
            'nbf' => time(), // 生效的开始时间
            'exp' => time() + 3600 * 24 * 10, // token过期时间
            'data' => [ // 自定义字段 根据自己的需求.
                'user_id' => $user_id,
                'user_type' => $user_type
            ]
        ];
        $jwt = JWT::encode($payload, $key, 'HS256');
        return $jwt;
    }

    public static function checkToken($jwt_token)
    {
        $key = 'example_key';

        JWT::$leeway = 60; // 延长1分钟有效期
        try {
            $decoded = JWT::decode($jwt_token, new Key($key, 'HS256'));
            $decoded_array = (array) $decoded;
            return ['status' => true, 'data' => $decoded_array, 'msg' => '验证成功'];
            return $decoded_array;
        } catch (SignatureInvalidException $e) {
            return ['status' => false, 'msg' => '验证失败，请重新登录。', 'code' => 401];
        } catch (BeforeValidException $e) {
            return ['status' => false, 'msg' => 'Token未生效，请稍后再试。', 'code' => 401];
        } catch (ExpiredException $e) {
            return ['status' => false, 'msg' => '登录过期，请重新登录。', 'code' => 401];
        } catch (Exception $e) {
            return ['status' => false, 'msg' => '验证出错[' . $e->getMessage() . ']', 'code' => 500];
        }
    }
}
